import { constantRoutes,asyncRoutes } from '@/router'
import store from '@/store'
import Layout from '@/layout'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}
const routeLoader = require.context('@/views', true, /\.vue$/)
async function generateRoutes(children, item) {
  let node;
  if (item.component) {
    node ={
        path: item.url,
        name: item.name,
        hidden: item.hidden,
        meta: {
          title: item.name,
          icon: item.icon
        },
        component: async () => await routeLoader(item.component.replace('@/views', '.') + '.vue').default,  //import(item.component), //
        children:[]
    }
    children.push(node)
  }else{
    node ={
      path: item.url,
      name: item.name,
      hidden: item.hidden,
      meta: {
        title: item.name,
        icon: item.icon
      },
      component:Layout,
      children:[]
    }
    children.push(node)
  }
  if (item.children) {
      item.children.forEach(e => {
          generateRoutes(node.children, e)
      })
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(async (resolve) => {
      let accessedRoutes = []
      const menus = store.getters && store.getters.menus
      for (let item of menus.list) {
        await generateRoutes(accessedRoutes,item)
      }
      accessedRoutes = accessedRoutes.concat(asyncRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
